package com.nuanshui.heatedloan.msgcenter.rabbitmq;

import com.nuanshui.heatedloan.msgcenter.integration.AppPushMsgBody;
import com.nuanshui.heatedloan.msgcenter.model.MsgType;
import com.nuanshui.heatedloan.msgcenter.model.SmsPushMsgBody;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.middleware.rabbitmq.RabbitmqMessageHandler;
import com.nuanshui.heatedloan.middleware.rabbitmq.annotation.MqMessageHandler;
import com.nuanshui.heatedloan.msgcenter.facade.MsgSender;
import com.nuanshui.heatedloan.middleware.msgcenter.bean.MsgBody;
import com.nuanshui.heatedloan.constant.RabbitMqQueue;

@MqMessageHandler(RabbitMqQueue.RABBIT_MQ_SEND_MSG)
public class MsgSendHandler implements RabbitmqMessageHandler{

	@Autowired
	private MsgSender msgSender;
	
	Logger logger = LoggerFactory.getLogger(MsgSendHandler.class);
	
	@Override
	public void onMessage(Message message, Channel channel) throws Exception {
		try{
			LogUtil.info(logger, "开始发送消息");
			
			String str = new String(message.getBody());
			if(StringUtils.isEmpty(str)) return ;

			MsgBody msgBody =JSON.parseObject(str, MsgBody.class);
			if(msgBody == null) return;

			if(msgBody.getMsgType()== MsgType.SMS_MSG)
			{
				msgBody = JSON.parseObject(str, SmsPushMsgBody.class);
			}
			else if(msgBody.getMsgType()== MsgType.PUSH_MSG)
			{
				msgBody = JSON.parseObject(str, AppPushMsgBody.class);
			}
			msgSender.sendPushMsg(msgBody);
			
			
		} catch(Exception e){
			LogUtil.error(logger, "发送消息失败！" + e);
		}
		
		channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
	}

}
